package com.example.baselib.utils

import android.content.Context
import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.baselib.activity.MyDao
import com.example.baselib.constants.MyConstants
import com.example.baselib.databean.Unitinfo
import java.util.concurrent.Executors

/**
 * Author: sxygsj
 * Date: 2020/8/26 15:16
 * Description: 数据库database
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
@Database(entities = [Unitinfo::class], version = 1, exportSchema = false)
abstract class UnitRoomDatabase : RoomDatabase() {
    abstract fun myDao(): MyDao
//单例
    companion object{
        private var INSTANCE: UnitRoomDatabase? = null
        private val NUMBER_OF_THREADS = 4
        internal val databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS)
        fun getDatabase(context: Context): UnitRoomDatabase {
            if (INSTANCE == null) {
                synchronized(UnitRoomDatabase::class.java) {
                    if (INSTANCE == null) {
                        INSTANCE = Room.databaseBuilder<UnitRoomDatabase>(
                            context,
                            UnitRoomDatabase::class.java, "unit.db"
                        )
                            .addCallback(sRoomDatabaseCallback)
                            .build()
                    }
                }
            }
            return INSTANCE!!
        }

        /**
         * @Description: [相当于初始化数据，先进行插入数据]
         * @Param:
         * @Return:
         */
        private val sRoomDatabaseCallback = object : RoomDatabase.Callback() {
            override fun onCreate(db: SupportSQLiteDatabase) {
                super.onCreate(db)
                databaseWriteExecutor.execute {
                    if (MyConstants.userData.usertype>1){
                        val insertAll = INSTANCE?.myDao()?.insertAll(MyConstants.userData.unitinfo)
                        Log.i("database+++++++",insertAll?.size.toString())
                    }

                }
            }
        }




    }




}